package record;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

//彩票记录类
//保存彩票号码和中将信息

public class NumbersRecord {

    private static final String NUMBER_RECORDS_FILE = "_number_records.txt";
   // private static final String WINNING_RECORDS_FILE = "winning_records.txt";
 // 将新彩票加入List<String> numbers
    public static void addNumberstoList(List<String> numbers, List<String> newNumbers) {
        for (String newNumber : newNumbers) {
            numbers.add(newNumber + "," + "未获奖");
        }
    }

   // 将新彩票保存到对应用户的彩票文件中
   public static void saveNumbersToFile(String username, List<String> newNumbers) {
       try (BufferedWriter writer = new BufferedWriter(new FileWriter(username + NUMBER_RECORDS_FILE, true))) {
           for (String newNumber : newNumbers) {
               writer.write(newNumber + "," + "未获奖");
               writer.newLine();
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

   // 将彩票信息从文件中读到List
   public static List<String> fileToList(String username){
       List<String> numbers = new ArrayList<>();
       try{
        String path =username+NUMBER_RECORDS_FILE;
        BufferedReader reader=new BufferedReader(
            new InputStreamReader(
                new FileInputStream(path),"UTF-8"));
            String line;
            while((line=reader.readLine())!=null){
               System.out.println(line);
               numbers.add(line);
            }
            reader.close();
      }catch(IOException e){
          e.printStackTrace();  
      }
      
      return numbers; 
  }

  // 将彩票信息从List中读到文件，并覆盖原有内容
  public static void listToFile(List<String> numbers, String username) {
      try  {
        BufferedWriter writer=new BufferedWriter(
            new OutputStreamWriter(
                new FileOutputStream(username+NUMBER_RECORDS_FILE),"UTF-8"));
          for (String number : numbers) {
              writer.write(number);
              writer.newLine();
          }
          writer.close();
     } catch (IOException e) { 
         e.printStackTrace(); 
     }
  }
}

